package edu.whut.mall.user.controller;

import edu.whut.mall.common.api.ResponseMap;
import edu.whut.mall.common.constant.FileConstant;
import edu.whut.mall.user.dto.UserDto;
import edu.whut.mall.user.service.IUserService;
import edu.whut.mall.user.service.ISecurityCodeService;
import edu.whut.mall.user.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author smq
 * @Date 2021/8/17 18:29
 * @Uint d9lab
 * @Description:
 */

@Api(tags = {"用户接口"}, description = "用户接口", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/user")
@Slf4j
public class UserController {

    private final IUserService userService;

    private final ISecurityCodeService ISecurityCodeService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(HttpServletRequest request, @RequestBody UserDto post) {
        ResponseMap map = ResponseMap.getInstance();
//        String code = request.getParameter("code");
        //这样写是为了方便测试，正规的应该都是从request请求中获取
        String code = post.getCode();
        Assert.state(StringUtils.isNotBlank(post.getEmail()), "请输入邮箱地址");
        Assert.state(StringUtils.isNotBlank(code), "请输入邮箱验证码");
        boolean res = ISecurityCodeService.verify(post.getEmail(), code);
        if (!res) return map.putFailure("验证码错误", 0);
        post.setPicture(FileConstant.AVATAR);
        UserVo userVo = userService.register(post);
//      Result<AccountProfile> result = executeLogin(post.getUsername(), post.getPassword(), false);
        return map.putValue(userVo, "注册成功");
    }
}
